package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.dtos.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.HistorySearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiaquanen
 * @version 1.0
 * @project heima-leadnews
 * @date 2024/7/30 10:37:12
 */
@Service
public class HistorySearchServiceImpl implements HistorySearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加搜索记录
     *
     * @param searchWords
     * @param userId
     */
    @Override
    @Async
    public void saveHistory(String searchWords, Integer userId) {
        //判断是不是游客登陆
        if(userId==null||userId==0)
            return;
        //封装数据
        ApUserSearch apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(searchWords);
        apUserSearch.setCreatedTime(new Date());
        //先查询用户之前有没有搜过
        List<ApUserSearch> ap = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), ApUserSearch.class);
        if(ap.isEmpty())
        {
            //表示数据库中没有该用户的数据直接添加即可
            mongoTemplate.save(apUserSearch);
        }else if(ap.size()<=9)
        {
            //表示数据没有到十条
            for (ApUserSearch userSearch : ap) {
                if(userSearch.getKeyword().equals(searchWords))
                {
                    userSearch.setCreatedTime(new Date());
                    mongoTemplate.save(userSearch);
                    return;
                }
            }
            //到这就没有该词
            mongoTemplate.save(apUserSearch);
            return;
        }
        for (ApUserSearch userSearch : ap) {
            if(userSearch.getKeyword().equals(searchWords))
            {
                userSearch.setCreatedTime(new Date());
                mongoTemplate.save(userSearch);
                return;
            }
        }
        //删除最后一条
        List<ApUserSearch> apUserSearches = ap.stream().sorted(Comparator.comparing(ApUserSearch::getCreatedTime)).collect(Collectors.toList());
        ApUserSearch apUserSearch1 = apUserSearches.get(0);
        mongoTemplate.remove(apUserSearch1);
        mongoTemplate.save(apUserSearch);
    }

    /**
     * 查询搜索记录
     *
     * @return
     */
    @Override
    public ResponseResult load() {
        Integer userId = AppThreadLocalUtil.getUserId();
        //判断是不是游客登陆
        if(userId==null||userId==0)
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Direction.DESC,"createdTime")), ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    /**
     * 删除搜索记录
     *
     * @param historySearchDto
     */
    @Override
    public void deleteHistory(HistorySearchDto historySearchDto) {
        mongoTemplate.remove(Query.query(Criteria.where("id").is(historySearchDto.getId())), ApUserSearch.class);
    }
}
